package soa.security.web.action;

import org.apache.commons.lang3.StringUtils;

import soa.security.domain.Role;
import soa.security.web.support.action.LdapModelAction;

/**
 * 
 * @author hueb
 *
 *         2015年4月22日
 */
public class RoleAction extends LdapModelAction<Role> {

	private static final long serialVersionUID = 7033329988062825005L;

	private String roleId;
	private String subRoleIds;

	public String grid() {
		if (StringUtils.isBlank(organizationId))
			return SUCCESS;

		if (StringUtils.isNotBlank(departmentId))
			updateResultContent(departmentMgrService.allRoles(organizationId,
					departmentId));
		else
			updateResultContent(roleMgrService.allRoles(organizationId));

		return SUCCESS;
	}

	public String edit() {
		Role role = getModel();
		if (StringUtils.isBlank(role.getBid())) {
			role.setBid("RO" + roleMgrService.findMaxNumber(Role.class));
		}
		updateResultContent(role);

		this.pageResult.addData("organizationId", organizationId);
		this.pageResult.addData("departmentId", departmentId);

		this.pageResult.addData("organizationName",
				getOrganization(organizationId).getName());
		this.pageResult.addData("departmentName",
				getDepartment(organizationId, departmentId).getName());

		return SUCCESS;
	}

	public String doneSave() {
		roleMgrService.addRole(organizationId, getModel());

		if (StringUtils.isNotBlank(departmentId))
			departmentMgrService.addRoles(organizationId, departmentId,
					getModel().getBid());

		roleMgrService.addOrRemove(organizationId, getModel().getBid(),
				personDns);
		roleMgrService.addOrRemoveSub(organizationId, getModel().getBid(),
				subRoleIds);

		return SUCCESS;
	}

	public String doneUpdate() {
		roleMgrService.updateRole(organizationId, getModel());
		roleMgrService.addOrRemove(organizationId, getModel().getBid(),
				personDns);
		roleMgrService.addOrRemoveSub(organizationId, getModel().getBid(),
				subRoleIds);

		return SUCCESS;
	}

	public String doneAddPersons() {
		roleMgrService.addPersons(organizationId, roleId, personDns);
		return SUCCESS;
	}

	public String doneRemovePersons() {
		roleMgrService.removePersons(organizationId, roleId, personDns);
		return SUCCESS;
	}

	public String doneAddGroups() {
		roleMgrService.removeAllSubRoles(organizationId, roleId);
		roleMgrService.addSubRoles(organizationId, roleId, subRoleIds);
		return SUCCESS;
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public String getSubRoleIds() {
		return subRoleIds;
	}

	public void setSubRoleIds(String subRoleIds) {
		this.subRoleIds = subRoleIds;
	}

	@Override
	protected Role findByDn(String dn) {
		return roleMgrService.findByDn(dn);
	}
}
